package cart

import (
	"encoding/json"
	// "fmt"
	"sort"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/moneyx"

	// enum "mall/service/backend/common/enum/promotion"
	"mall/common/utils/pointy"
	"mall/service/forum/api/internal/logic/promotion/util"
	"mall/service/forum/api/internal/types"
	"mall/service/promotion/rpc/promotionclient"

	"github.com/shopspring/decimal"
	// "github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

// PromotionInfoHandler 获取优惠信息handler
type PromotionInfoHandler struct {
	// 合成复用Next
	Next
}

// Do 获取优惠信息
func (h *PromotionInfoHandler) Do(c *Context) (err error) {
	// logx.Infow("获取优惠信息...")

	preload := "activity:Id,Name,Desc,Members,Type,Mutex,Scope,TimesLimit,GroupMode,GroupType,StartedAt,EndedAt"
	eagerLoad := "activity:ruleGroup,logTotal"
	filters := []string{"Status,equalTo:" + strconv.FormatInt(int64(globalkey.StatusStarted), 10)}

	res, err := c.SvcCtx.PromotionRpc.GetActivityList(c.Ctx, &promotionclient.BaseListReq{
		Preload:    pointy.GetPointer(preload),
		EagerLoad:  pointy.GetPointer(eagerLoad),
		Filter:     pointy.GetPointer(strings.Join(filters, ";")),
		Sorter:     pointy.GetPointer("Sort:1;Id:1"),
		VisitorId:  pointy.GetPointer(c.UserId),
		PlatformId: pointy.GetPointer(globalkey.ThirdPartyPlatformWechatMini),
	})
	if err != nil {
		return err
	}

	if len(res.List) > 0 {
		for _, v := range res.List {
			if v.TimesLimit != nil && v.LogTotal != nil && *v.TimesLimit > 0 && *v.LogTotal >= *v.TimesLimit {
				continue
			}

			var timeRange []string
			if v.StartedAt != nil && v.EndedAt != nil {
				timeRange = []string{*v.StartedAt, *v.EndedAt}
			}

			activityTypeText := util.GetActivityTypeText(v.ActivityType)
			mutexTypeText := util.GetMutexTypeText(v.MutexType)
			scopeTypeText := util.GetScopeTypeText(v.ScopeType)
			groupModeText := util.GetGroupModeText(v.GroupMode)
			groupTypeText := util.GetGroupTypeText(v.GroupType)

			var groups []*types.PromotionActivityRuleGroupInfo
			if len(v.Groups) > 0 {
				for _, group := range v.Groups {
					var rules []*types.PromotionActivityRuleInfo
					if len(group.Rules) > 0 {
						for _, rule := range group.Rules {
							var regions []*types.TreeNode
							if rule.Regions != nil {
								if err := json.Unmarshal([]byte(*rule.Regions), &regions); err != nil {
									logx.Errorw("PromotionInfoHandler Rules.Regions json.Unmarshal err",
										logx.Field("detail", err.Error()))
								}
							}

							ruleTypeText := util.GetRuleTypeText(rule.RuleType)
							ruleModeText := util.GetRuleModeText(rule.RuleType, rule.Mode)
							rules = append(rules, &types.PromotionActivityRuleInfo{
								Id:           rule.Id,
								Regions:      regions,
								RuleType:     rule.RuleType,
								RuleTypeText: pointy.GetPointer(ruleTypeText),
								Mode:         rule.Mode,
								RuleModeText: pointy.GetPointer(ruleModeText),
								Value:        rule.Value,
								Sort:         rule.Sort,
							})
						}
					}

					var threshold decimal.Decimal
					if group.Threshold != nil {
						if ft, err := moneyx.ParseDecimal(*group.Threshold); err == nil {
							threshold = ft
						}
					}
					groups = append(groups, &types.PromotionActivityRuleGroupInfo{
						Id:           group.Id,
						Threshold:    group.Threshold,
						ComThreshold: threshold,
						Sort:         group.Sort,
						Rules:        rules,
					})
					sort.Slice(groups, func(i, j int) bool {
						return groups[i].ComThreshold.(decimal.Decimal).GreaterThan(groups[j].ComThreshold.(decimal.Decimal))
					})
				}
			}

			c.Resp.ActivityList = append(c.Resp.ActivityList, &types.PromotionActivityInfo{
				Id:                v.Id,
				Name:              v.Name,
				Description:       v.Description,
				MemberRestriction: v.MemberRestriction,
				ActivityType:      v.ActivityType,
				ActivityTypeText:  pointy.GetPointer(activityTypeText),
				MutexType:         v.MutexType,
				MutexTypeText:     pointy.GetPointer(mutexTypeText),
				ScopeType:         v.ScopeType,
				ScopeTypeText:     pointy.GetPointer(scopeTypeText),
				TimesLimit:        v.TimesLimit,
				GroupMode:         v.GroupMode,
				GroupModeText:     pointy.GetPointer(groupModeText),
				GroupType:         v.GroupType,
				GroupTypeText:     pointy.GetPointer(groupTypeText),
				TimeRange:         timeRange,
				Status:            pointy.GetPointer(uint32(globalkey.StatusStarted)),
				Groups:            groups,
			})
		}
	}

	return
}
